package party.lovey.remote.amq;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.Session;

/**
 * Created by huhaichao on 2017/3/19.
 */
public class SessionFactory {
    // ConnectionFactory ：连接工厂，JMS 用它创建连接
    private static ConnectionFactory connectionFactory;
    // Session： 一个发送或接收消息的线程
    private static Session senderSession;
    private static Session receiverSession;

    private static synchronized ConnectionFactory getConnectionFactory() {
        if (connectionFactory != null) {
            return connectionFactory;
        }

        // 构造ConnectionFactory实例对象，此处采用ActiveMq的实现jar
        connectionFactory = new ActiveMQConnectionFactory(
                ActiveMQConnection.DEFAULT_USER,
                ActiveMQConnection.DEFAULT_PASSWORD,
                ActiveMQConnection.DEFAULT_BROKER_URL);

        return connectionFactory;
    }

    public static synchronized Session getSenderSession() {

        if(senderSession!=null){
            return senderSession;
        }

        connectionFactory = getConnectionFactory();

        // Connection ：JMS 客户端到JMS Provider 的连接
        Connection connection = null;

        try {
            // 构造从工厂得到连接对象
            connection = connectionFactory.createConnection();
            // 启动
            connection.start();
            // 获取操作连接
            senderSession = connection.createSession(Boolean.TRUE,
                    Session.AUTO_ACKNOWLEDGE);
        } catch (JMSException e) {
            e.printStackTrace();
        }

        return senderSession;
    }


    public static synchronized Session getReceiverSession() {



        connectionFactory = getConnectionFactory();

        // Connection ：JMS 客户端到JMS Provider 的连接
        Connection connection = null;

        try {
            // 构造从工厂得到连接对象
            connection = connectionFactory.createConnection();
            // 启动
            connection.start();
            // 获取操作连接
            receiverSession = connection.createSession(Boolean.FALSE,
                    Session.AUTO_ACKNOWLEDGE);
        } catch (JMSException e) {
            e.printStackTrace();
        }

        return receiverSession;
    }
}
